package com.javaweb.newservlelt;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * LoginServlet for login request.
 * there are two ways for configuring servlet
 *  A. in web.xml
 *  B. @WebServlet
 */

@WebServlet( "/test/rating")
public class RatingAjaxServlet extends HttpServlet {
    private Logger logger = LogManager.getLogger(RatingAjaxServlet.class) ;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp) ;
    }
    /**
     * override doPost logic from father by our own business logic
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // the request string format:  rating=xxx&comment=xxxx
        req.setCharacterEncoding("utf-8");
        String requestString = readRequestString(req) ;
        String tokens [] = requestString.split("&") ;
        String rating = tokens[0] ;
        String comment = tokens[1] ;
        logger.debug("got parameter : {}  {} " , rating, comment );
        // generate response string, just an example.
        String retString = rating + "&" + comment + "&" + "work hard" ;
        resp.setContentType("application/text; charset=utf-8");
        PrintWriter out = resp.getWriter() ;
        out.print(retString) ;
        out.flush() ;
    }

    /**
     * Read data string from request body.
     * For GET request, the method of 'getParameter' could read parameter from request, however, it did not work
     * for POST request.
     * @param req
     * @return
     * @throws Exception
     */
    private String readRequestString(HttpServletRequest req) throws IOException {

        BufferedReader reader = req.getReader() ;
        String line ;
        StringBuilder stringBuilder = new StringBuilder() ;
        while ((line = reader.readLine()) != null ) {
            stringBuilder.append(line) ;
        }
        return stringBuilder.toString() ;



    }



}





